﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Roovent.HttpOperator
{
	public class FormParser
	{
		private string content;
		private HtmlForm form;

		public HtmlForm FormLabel
		{
			get
			{
				if (form == null)
				{
					ParseForm();
				}
				return form;
			}
		}

		public FormParser(string content)
		{
			//当没有匹配项时Match对象并不会为空，而是匹配到的字符串为空字符串
			Match m = Regex.Match(content, @"<form[^>]+>(.|\n)*</form>", RegexOptions.IgnoreCase);
			if (m.Length > 0)
			{
				this.content = m.Value;
			}
			else
			{
				throw new ArgumentException();
			}
		}

		private void ParseForm()
		{
			Match m = Regex.Match(content, @"<form[^>]+>", RegexOptions.IgnoreCase);
			form = new HtmlForm(m.Value);
			HtmlInput[] inputs = ParseInput();
			foreach (HtmlInput input in inputs)
			{
				form.Labels.Add(input);
			}
		}

		public static HtmlForm ParseForm(string content)
		{
			return new FormParser(content).FormLabel;
		}

		private HtmlInput[] ParseInput()
		{
			MatchCollection mc = Regex.Matches(content, @"<input[^>]+>", RegexOptions.IgnoreCase);
			HtmlInput[] inputs = new HtmlInput[mc.Count];
			for (int i = 0; i < mc.Count; ++i)
			{
				inputs[i] = new HtmlInput(mc[i].Value);
			}
			return inputs;
		}
	}
}
